namespace IQIGame.Onigao.Game
{
    public class PackageHeader
    {
        public PackageHeader() { }

        public int Length;
        public int Messagid;
        public int Order;

        public int HeaderSize
        {
            get
            {
                return 4 + 4 + 4;
            }
        }

        public void Init(byte[] bytes, int offset)
        {
            Length = ReadInt(bytes, offset);
            Messagid = ReadInt(bytes, offset + 4);
            Order = ReadInt(bytes, offset + 8);
        }

        public void InitWithoutHeadLength(byte[] bytes, int offset)
        {
            Messagid = ReadInt(bytes, offset);
            Order = ReadInt(bytes, offset + 4);
        }

        public byte[] GetBytes()
        {
            byte[] bytes = new byte[HeaderSize];
            PutInt(bytes, 0, Length);
            PutInt(bytes, 4, Messagid);
            PutInt(bytes, 8, Order);
            return bytes;
        }

        private static int ReadInt(byte[] bytes, int offset)
        {
            int value = 0;
            value |= bytes[offset] & 0xff;
            value |= (bytes[1 + offset] & 0xff) << 8;
            value |= (bytes[2 + offset] & 0xff) << 16;
            value |= (bytes[3 + offset] & 0xff) << 24;
            return value;
        }

        private static void PutInt(byte[] bytes, int offset, int value)
        {
            bytes[offset] = (byte)(value & 0xff);
            bytes[1 + offset] = (byte)((value >> 8) & 0xff);
            bytes[2 + offset] = (byte)((value >> 16) & 0xff);
            bytes[3 + offset] = (byte)((value >> 24) & 0xff);
        }

        public void Clear()
        {
            Length = 0;
            Messagid = 0;
            Order = 0;
        }
    }
}
